#include <iostream>
#include "./linked-queue.h"

void initLinkedQueue(LinkedQueue &queue)
{
	queue.front = queue.rear = new QNode;
	queue.front->data = 0;
	queue.front->next = nullptr;
}

int linkedQueueEmpty(LinkedQueue &queue)
{
	return queue.front == queue.rear;
}

int linkedQueueLength(LinkedQueue &queue)
{
	QNode *pointer = queue.front;
	int length = 0;
	while (pointer->next != nullptr)
	{
		pointer = pointer->next;
		length++;
	}
	return length;
}

ElemType getLinkedQueueHead(LinkedQueue &queue)
{
	return queue.front->data;
}

void enterLinkedQueue(LinkedQueue &queue, ElemType e)
{
	QNode *node = new QNode;
	node->data = e;
	node->next = nullptr;
	queue.rear->next = node;
	queue.rear = node;
}

ElemType goOutLinkedQueue(LinkedQueue &queue)
{
	if (linkedQueueEmpty(queue))
	{
		return 0;
	}
	// 要被删除的元素
	QNode *p = queue.front->next;
	ElemType e = p->data;
	queue.front->next = p->next;
	// 当队列只有一个元素时，删除队头指针会导致队尾一起被删除，因此需要重置队尾指针
	if (queue.rear == p)
	{
		queue.rear = queue.front;
	}
	delete p;
	return e;
}

void linkedQueueTraverse(LinkedQueue &queue, void (*visit)(ElemType &e))
{
	QNode *pointer = queue.front;
	while (pointer->next != nullptr)
	{
		visit(pointer->next->data);
		pointer = pointer->next;
	}
}